package com.ug.system.processor;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ug.common.cache.redis.RedisCacheService;
import com.ug.common.constant.HotConstants;
import com.ug.common.utils.SpringContextHolder;
import com.ug.system.entity.AttributeValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author: LY
 * @description: 澎湃新闻爬取
 */
public class PengpaiHotHtmlPageProcessor {

    private static final Logger logger = LoggerFactory.getLogger(PengpaiHotHtmlPageProcessor.class);
    private static final RedisCacheService redisCacheService = SpringContextHolder.getBean(RedisCacheService.class);

    /**
     * 澎湃新闻热门数据爬取
     */
    public static List<AttributeValue> hotToDayProcessor(){
        logger.info("获取澎湃新闻热门数据");
        String key = HotConstants.HOT_TYPE_PENG_PAI.concat(HotConstants.HOT_TYPE_KEY);
        try {
            String result = HttpRequest.get(HotConstants.PENG_PAI_HOT_URL)
                    .timeout(5000)
                    .execute().body();
            JSONObject jsonObject = JSONObject.parseObject(result);
            Object o = jsonObject.get("data");
            JSONObject data = JSONObject.parseObject(o.toString());
            Object o1 = data.getString("hotNews");
            JSONArray list = JSONArray.parseArray(o1.toString());
            List<AttributeValue> attributeValues = new ArrayList<>();
            for (int i = 0; i < list.toArray().length; i++) {
                Object o2 = list.get(i);
                JSONObject jsonObject1 = JSONObject.parseObject(o2.toString());
                String title = jsonObject1.getString("name");
                String contId = jsonObject1.getString("contId");
                String link = "https://www.thepaper.cn/newsDetail_forward_" + contId;
                String value = "0";
                AttributeValue attributeValue = new AttributeValue(title, link, value);
                attributeValues.add(attributeValue);
            }
            redisCacheService.put(key, attributeValues, HotConstants.HOT_TIME_OUT, TimeUnit.HOURS);
            return attributeValues;
        }catch (Exception e){
            logger.error("获取澎湃新闻热门数据异常：{}", e.getMessage());
        }
        return null;
    }
}
